<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use app\common\model\ActsOrder as ActsOrderModel;
use app\common\model\Recharge as RechargeModel;
use app\common\model\Act as ActModel;
use think\Controller;

/**
 * 项目订单控制器
 * Class Companyxuyuan
 * @package app\home\controller
 */
class Actsorder extends Controller
{
    /**
     * [pay  微信支付]
     * @param
     * @return json
     * @author [C。]
     */
    public function pay()
    {
        $param = input('param.');
        $amodel = new ActModel;
        $rmodel = new RechargeModel();
        $omodel = new ActsOrderModel;
        try{
            $act = $amodel->findData($param['id'],'id','title,comid,amount');
            $hasamount1 = $omodel->getAlreadyRaising($param['id']);
            $hasamount2 = $rmodel->getAlreadyRaising($param['id']);
            $candonate = $act['amount'] - $hasamount1 - $hasamount2;
            if($candonate == 0){
                return admin_json(-1, '捐款金额已足够，请下次再来！');
            }elseif(intval($param['money']) > $candonate){
                return admin_json(-1, '该项目还可捐'.$candonate.'元，请修改金额再试！');
            }

            $appid = config('home.appid');
            $openid = $param['openid'];
            $mch_id = config('home.mch_id');
            $key = config('home.mch_secret');
            $out_trade_no = date('Ymd') . time().str_pad(mt_rand(1, 99999), 5, '0');
            $body = $act['title'];
            $total_fee = $param['money'] * 100;
            $trade_type = 'JSAPI';
            $weixinpay = new \WeixinPay\WeixinPay($appid,$openid,$mch_id,$key,$out_trade_no,$body,$total_fee,$trade_type);
            $return = $weixinpay->pay();
        }catch(\Exception $e){
            systembug($e->getMessage(),2,'home/Actsorder/pay');
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        if(is_array($return)){
            $return['aid'] = $param['id'];
            $return['comid'] = $act['comid'];
            $return['money'] = $param['money'];
            $return['ordernum'] = $out_trade_no;
        }
        if($return){
            return admin_json(1, '获取成功',$return);
        }else{
            return admin_json(-1, '获取失败');
        }
    }
    /**
     * [auth  微信授权]
     * @param
     * @return json
     * @author [C。]
     */
    public function auth()
    {
        $param = input('param.');
        $code = $param['code'];
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . config('home.appid') . '&secret=' . config('home.secret') . '&code=' . $code . '&grant_type=authorization_code';
        $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据，推荐使用curl
        $json = json_decode($info);//对json数据解码
        $arr = get_object_vars($json);
        if (empty($arr['access_token'])) {
            return admin_json('-1', $arr);
        }
        $access_token = $arr['access_token'];
        $openid = $arr['openid'];
        $user_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user_info = file_get_contents($user_url);//发送HTTPs请求并获取返回的数据，推荐使用curl
        $user_json = json_decode($user_info);//对json数据解码
        $user_arr = get_object_vars($user_json);
        return admin_json(1, '获取成功',$user_arr);
    }
    /**
     * [getCheck  微信查询订单]
     * @param
     * @return json
     * @author [C。]
     */
    public function check()
    {
        $param = input('param.');
        $amodel = new ActModel;
        $model = new ActsOrderModel();
        $rmodel = new RechargeModel();
        $omodel = new ActsOrderModel;
        try{
            $appid = config('home.appid');//开放平台appid
            $mch_id = config('home.mch_id');  //商户号
            $key = config('home.mch_secret');  //商户密钥
            $out_trade_no = $param['ordernum'];
            $weixinpay = new \WeixinPay\WeixinPay($appid,$openid = '',$mch_id,$key,$out_trade_no,$body = '',$total_fee = '');
            $return = $weixinpay->check();
        }catch(\Exception $e){
            systembug($e->getMessage(),2,'home/Actsorder/check');
            return admin_json(-1, '查询失败'.$e->getMessage());
        }
        if($return){
            if($return['return_code'] == "SUCCESS"){
                if(!empty($return['trade_state'])){
                    if($return['trade_state'] == "SUCCESS"){
                        $actorder = $model->findData($param['ordernum'],'ordernum');
                        if(empty($actorder)){
                            $model->addData($param);
                            $act = $amodel->findData($param['aid'],'id','amount');
                            $hasamount1 = $omodel->getAlreadyRaising($param['aid']);
                            $hasamount2 = $rmodel->getAlreadyRaising($param['aid']);
                            $hasamount = $act['amount'] - $hasamount1 - $hasamount2;
                            if($hasamount <= 0){
                                $amodel->editData(['id'=>$param['aid'],'states'=>3]);
                            }
                        }
                        return admin_json(1, '订单支付成功');
                    }else{
                        return admin_json(-1, '订单支付失败');
                    }
                }else{
                    return admin_json(-1, '订单支付失败');
                }
            }else{
                return admin_json(-1, '订单支付失败');
            }
        }else{
            return admin_json(-1, '订单支付失败');
        }
    }
    public function reund()
    {
        $param = input('param.');
        $appid = config('home.appid');//开放平台appid
        $mch_id = config('home.mch_id');  //商户号
        $key = config('home.mch_secret');  //商户密钥
        $out_trade_no = $param['ordernum'];
        $price = $param['price']*100;
        $out_refund_no = date('Ymd') . time().str_pad(mt_rand(1, 99999), 5, '0');
        $weixinpay = new \WeixinPay\WeixinRefund($appid,$mch_id, $key, $out_trade_no, $price,$out_refund_no,$price);
        $return = $weixinpay->refund();
        echo '<pre>';
        print_r($return);
    }
}